const { createCommentDao, deleteCommentDao, getCommentPagingDao, getBlogCommentCountDao } = require("../dao/commentDao");
const { formatResponseBody } = require("../utils/tools");
const { Op } = require("sequelize");
const { getRandomAvatarPath } = require("../utils/tools");
const { ValidationError } = require("../utils/errors");
const { validate } = require("validate.js");
const { findOnBlogDao } = require("../dao/blogDao");


validate.validators.isExistBlogId = async (value, options, key, attr) => {
    const result = await findOnBlogDao(value);
    if (!result) return "blogId does not exist";
}

const rule = {
    nickname: {
        type: "string",
        presence: {
            allowEmpty: false,
        }
    },
    content: {
        type: "string",
        presence: {
            allowEmpty: {
                allowEmpty: false,
            }
        }
    },
    blogId: {
        isExistBlogId: true
    }
}

/**
 * 新增一条评论
 * @param {Object} comment 
 * @returns 
 */
exports.createCommentService = async (comment) => {
    try {
        // 验证传入的数据
        await validate.async(comment, rule);

        // 验证成功后初始化一些数据
        comment.createDate = Date.now();
        comment.avatar = getRandomAvatarPath();

        // 文章对应的评论数要新增
        const blog = await findOnBlogDao(comment.blogId);
        blog.commentNumber++;
        await blog.save();

        return formatResponseBody({ data: await createCommentDao(comment) });

    } catch (err) {
        throw new ValidationError("数据验证失败");
    }



}

/**
 * 删除一条评论
 * @param {number} id 
 * @returns 
 */
exports.deleteCommentService = async (id) => {
    const result = await deleteCommentDao(id);
    return formatResponseBody({ data: !!result });
}

/**
 * 分页获取评论
 * @param {object} param0 
 * @returns 
 */
exports.getCommentPagingService = async ({ page = 1, limit = 10, blogid = -1, keyword }) => {
    // 1. 根据条件组装where对象
    const where = {};
    if (blogid && blogid !== -1) {
        where.blogId = blogid;
    }
    if (keyword) {
        where.content = {
            [Op.like]: `%${keyword}%`
        }
    }

    // 2. 分页查询数据
    const result = await getCommentPagingDao((page - 1) * limit, +limit, where);

    // 3. 组装响应对象
    const data = {
        total: result.count,
        rows: result.rows.map(item => item.dataValues),
    }
    return formatResponseBody({ data })
}